<template>
  <div class="dashboard">
    <el-row :gutter="20">
      <!-- 航线分布图 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header">
            <span>航线分布图</span>
          </div>
          <div class="chart-container">
            <div ref="routeChart" style="width: 100%; height: 100%;"></div>
          </div>
        </el-card>
      </el-col>

      <!-- 票价分布图 -->
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <div slot="header">
            <span>票价分布图</span>
          </div>
          <div class="chart-container">
            <div ref="priceChart" style="width: 100%; height: 100%;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 航班时间分布图 -->
      <el-col :span="24">
        <el-card class="chart-card" shadow="hover">
          <div slot="header">
            <span>航班时间分布图</span>
          </div>
          <div class="chart-container">
            <div ref="timeChart" style="width: 100%; height: 100%;"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'Big',
  data() {
    return {
      // 模拟数据
      mockFlightData: [
        { cname: 'MU5735', cfrom: '北京', cto: '上海', crent: 800, start: '2024-01-01 08:00:00' },
        { cname: 'CZ3103', cfrom: '广州', cto: '成都', crent: 1200, start: '2024-01-01 09:30:00' },
        { cname: 'CA1234', cfrom: '上海', cto: '深圳', crent: 1500, start: '2024-01-01 10:00:00' },
        { cname: 'MU2345', cfrom: '北京', cto: '广州', crent: 1800, start: '2024-01-01 11:30:00' },
        { cname: 'CZ5678', cfrom: '成都', cto: '杭州', crent: 900, start: '2024-01-01 13:00:00' },
        { cname: 'CA9012', cfrom: '深圳', cto: '北京', crent: 2000, start: '2024-01-01 14:30:00' },
        { cname: 'MU3456', cfrom: '杭州', cto: '成都', crent: 1100, start: '2024-01-01 16:00:00' },
        { cname: 'CZ7890', cfrom: '广州', cto: '上海', crent: 1300, start: '2024-01-01 17:30:00' }
      ],
      flightData: [],
      charts: {
        routeChart: null,
        priceChart: null,
        timeChart: null
      }
    }
  },
  mounted() {
    this.fetchData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 清理事件监听
    window.removeEventListener('resize', this.handleResize)
    // 销毁图表
    Object.values(this.charts).forEach(chart => {
      chart && chart.dispose()
    })
  },
  methods: {
    handleResize() {
      Object.values(this.charts).forEach(chart => {
        chart && chart.resize()
      })
    },
    async fetchData() {
      try {
        const res = await request.get('/car/list')
        if (res.code === 0 && res.data && res.data.length > 0) {
          this.flightData = res.data
        } else {
          this.flightData = this.mockFlightData
        }
        this.$nextTick(() => {
          this.initCharts()
        })
      } catch (error) {
        console.error('获取航班数据失败:', error)
        this.flightData = this.mockFlightData
        this.$nextTick(() => {
          this.initCharts()
        })
      }
    },

    initCharts() {
      this.initRouteChart()
      this.initPriceChart()
      this.initTimeChart()
    },

    initRouteChart() {
      const cityCount = {}
      this.flightData.forEach(flight => {
        cityCount[flight.cfrom] = (cityCount[flight.cfrom] || 0) + 1
        cityCount[flight.cto] = (cityCount[flight.cto] || 0) + 1
      })

      const data = Object.entries(cityCount).map(([name, value]) => ({ name, value }))
      
      if (this.charts.routeChart) {
        this.charts.routeChart.dispose()
      }
      
      this.charts.routeChart = this.$echarts.init(this.$refs.routeChart)
      this.charts.routeChart.setOption({
        title: {
          text: '城市航班分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} 班次 ({d}%)'
        },
        series: [{
          type: 'pie',
          radius: '65%',
          center: ['50%', '50%'],
          data: data,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      })
    },

    initPriceChart() {
      const priceRanges = [
        { range: '0-500', count: 0 },
        { range: '501-1000', count: 0 },
        { range: '1001-1500', count: 0 },
        { range: '1501-2000', count: 0 },
        { range: '2000以上', count: 0 }
      ]

      this.flightData.forEach(flight => {
        const price = flight.crent
        if (price <= 500) priceRanges[0].count++
        else if (price <= 1000) priceRanges[1].count++
        else if (price <= 1500) priceRanges[2].count++
        else if (price <= 2000) priceRanges[3].count++
        else priceRanges[4].count++
      })

      if (this.charts.priceChart) {
        this.charts.priceChart.dispose()
      }

      this.charts.priceChart = this.$echarts.init(this.$refs.priceChart)
      this.charts.priceChart.setOption({
        title: {
          text: '票价分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: priceRanges.map(item => item.range)
        },
        yAxis: {
          type: 'value',
          name: '航班数量'
        },
        series: [{
          data: priceRanges.map(item => item.count),
          type: 'bar',
          barWidth: '40%',
          itemStyle: {
            color: '#409EFF'
          }
        }]
      })
    },

    initTimeChart() {
      const hourCount = new Array(24).fill(0)
      
      this.flightData.forEach(flight => {
        if (flight.start) {
          const hour = new Date(flight.start).getHours()
          hourCount[hour]++
        }
      })

      if (this.charts.timeChart) {
        this.charts.timeChart.dispose()
      }

      this.charts.timeChart = this.$echarts.init(this.$refs.timeChart)
      this.charts.timeChart.setOption({
        title: {
          text: '航班时间分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: '{b}时: {c}班'
        },
        xAxis: {
          type: 'category',
          data: Array.from({length: 24}, (_, i) => `${i}`)
        },
        yAxis: {
          type: 'value',
          name: '航班数量'
        },
        series: [{
          data: hourCount,
          type: 'line',
          smooth: true,
          symbolSize: 8,
          itemStyle: {
            color: '#67C23A'
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(103,194,58,0.3)'
              }, {
                offset: 1,
                color: 'rgba(103,194,58,0.1)'
              }]
            }
          }
        }]
      })
    }
  }
}
</script>

<style lang="less" scoped>
.dashboard {
  padding: 20px;
  background-color: #f5f7fa;

  .chart-card {
    margin-bottom: 20px;
    
    /deep/ .el-card__header {
      padding: 15px 20px;
      border-bottom: 1px solid #ebeef5;
      
      span {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }

    .chart-container {
      height: 400px;
      padding: 20px;
    }
  }
}

// 响应式布局
@media screen and (max-width: 1200px) {
  .dashboard {
    .el-col {
      width: 100% !important;
    }
  }
}
</style>
